package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongdb.CommentApi;
import com.tanhua.api.mongdb.PublishApi;
import com.tanhua.domain.UserHolder;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.Comment;
import com.tanhua.domain.mogo.Publish;
import com.tanhua.domain.vo.CommentVo;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.template.OssTemplate;
import com.tanhua.utils.RelativeDateFormat;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QuanZiService {

    @Autowired
    private OssTemplate ossTemplate;

    @Reference
    private PublishApi publishApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 发布动态   state: 0 未审核  1 审核通过  2 审核失败
    public ResponseEntity movements(Publish publish, MultipartFile[] imageContent) throws IOException {

        // 上传图片到oss中
        List<String> urlList=new ArrayList<>();
        if(imageContent!=null){
            for (MultipartFile multipartFile : imageContent) {
                String oss_url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                urlList.add(oss_url);
            }
        }
        // 设置publish的属性
        publish.setMedias(urlList);
        publish.setUserId(UserHolder.findUser().getId());
        publish.setState(0); //未审核
        // 调用服务保存方法
        String publishId=publishApi.save(publish); //保存数据到数据（文本 图片 审核状态了）

        //生成者生成消息到中间件中
        rocketMQTemplate.convertAndSend("tanhua-quanzi",publishId);

        return ResponseEntity.ok(null);
    }


    //查查我的动态
    public ResponseEntity findAlbumByPage(Integer page, Integer pagesize, Long userId) {

        // 分页查询到当前登录用户的详情数据
        PageBeanVo pageBean=publishApi.findAlbumByPage(page,pagesize,userId);
        List<Publish> items = (List<Publish>) pageBean.getItems();

        List<PublishVo> voList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            //用户
            UserInfo userInfo = userInfoApi.findByUser(userId);
            for (Publish publish : items) {
                    // 封装userInfo--publishVo
                PublishVo publishVo = new PublishVo();
                BeanUtils.copyProperties(userInfo,publishVo);
                publishVo.setTags(userInfo.getTags().split(","));
                    // 封装publish--publishVo
                BeanUtils.copyProperties(publish,publishVo);
                publishVo.setId(publish.getId().toString());
                String[] ImageContent = publish.getMedias().toArray(new String[]{});
                publishVo.setImageContent(ImageContent);
                publishVo.setDistance("5.12公里");
                publishVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                if(publish.getState()==1){
                        //信息是审核通过的
                    voList.add(publishVo);
                }

            }
        }

        //重新覆盖pageBean
        pageBean.setItems(voList);


        return ResponseEntity.ok(pageBean);
    }

    public ResponseEntity findTimeLineByPage(Integer page, Integer pagesize, Long userId) {

        // 1 分页获取publish数据
        PageBeanVo pageBean = publishApi.findTimeLineByPage(page, pagesize, userId);

        // 2 获取userInfo数据
        List<Publish> items = (List<Publish>) pageBean.getItems();

        List<PublishVo> publishVoList=new ArrayList<PublishVo>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Publish publish : items) {
                UserInfo userInfo = userInfoApi.findByUser(publish.getUserId());
                //3 数据封装publishVo
                PublishVo publishVo = new PublishVo();

                publishVo.setUserInfo(userInfo);
                publishVo.setPublish(publish);
                if(stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}",userId,publish.getId()))){
                    publishVo.setHasLiked(1); //是否点赞 0没点赞图标为灰色  1点赞了图标为高亮
                }else{
                    publishVo.setHasLiked(0); //是否点赞 0没点赞图标为灰色  1点赞了图标为高亮
                }

                publishVoList.add(publishVo);
            }
        }

        //4 返回pageBean<publishVo>
        pageBean.setItems(publishVoList);
        return ResponseEntity.ok(pageBean);
    }

    public ResponseEntity findRecommendByPage(Integer page, Integer pagesize, Long userId) {


        //从redis中查询数据返回（大数据推荐的）
        PageBeanVo pageBean=fromRedis(userId,page,pagesize);

        if(pageBean==null){
            // 1 分页获取publish数据（没推荐 查我们之前的假数据）
            pageBean = publishApi.findRecommendByPage(page, pagesize, userId);
        }


        // 2 获取userInfo数据
        List<Publish> items = (List<Publish>) pageBean.getItems();

        List<PublishVo> publishVoList=new ArrayList<PublishVo>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Publish publish : items) {
                UserInfo userInfo = userInfoApi.findByUser(publish.getUserId());
                //3 数据封装publishVo
                PublishVo publishVo = new PublishVo();

                publishVo.setUserInfo(userInfo);
                publishVo.setPublish(publish);

                //点赞
                if(stringRedisTemplate.hasKey(StrUtil.format("publish_like_comment_{}_{}",userId,publish.getId()))){
                    publishVo.setHasLiked(1); //是否点赞 0没点赞图标为灰色  1点赞了图标为高亮
                }else{
                    publishVo.setHasLiked(0); //是否点赞 0没点赞图标为灰色  1点赞了图标为高亮
                }

                //喜爱
                if(stringRedisTemplate.hasKey(StrUtil.format("publish_love_comment_{}_{}",userId,publish.getId()))){
                    publishVo.setHasLoved(1); //是否点赞 0没点赞图标为灰色  1点赞了图标为高亮
                }else{
                    publishVo.setHasLoved(0); //是否点赞 0没点赞图标为灰色  1点赞了图标为高亮
                }

                publishVoList.add(publishVo);
            }
        }
        //4 返回pageBean<publishVo>
        pageBean.setItems(publishVoList);
        return ResponseEntity.ok(pageBean);

    }

    //从redis中获取到大数据给的推荐圈子数据
    private PageBeanVo fromRedis(Long userId, Integer page, Integer pagesize) {

        String value = stringRedisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + userId);
        if(value==null){
            return null;
        }
        String[] pids = value.split(",");
        Integer count=pids.length;

        int start=(page-1)*pagesize;
        if(start>count){
            return null;
        }
        int end=page*pagesize;
        if(end>count){
            end=count;
        }
        //根据指定的分页查询publish圈子数据
        List<Publish> publisthList=new ArrayList<>();
        for(int i=start;i<end;i++){
            Publish publish=publishApi.findByPid((Long.parseLong(pids[i])));
            publisthList.add(publish);
        }

        return new PageBeanVo(page,pagesize,count.longValue(),publisthList);
    }

    @Reference
    private CommentApi commentApi;

    public ResponseEntity commentLike(String publishId) {
        //设置点赞的可变属性
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        Long userId = UserHolder.findUser().getId();
        comment.setUserId(userId);
        comment.setPubType(1);
        comment.setCommentType(1);
        Integer count = commentApi.save(comment);

        //放入redis代表当前登录用户对某个动态点过赞 "comment_like_登录用户_动态id"
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_like_comment_{}_{}",userId,publishId),"1"); //1代表点赞

        return ResponseEntity.ok(count);
    }

    public ResponseEntity dislikeLike(String publishId) {
        //设置点赞的可变属性
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        Long userId = UserHolder.findUser().getId();
        comment.setUserId(userId);
        comment.setPubType(1);
        comment.setCommentType(1);
        Integer count = commentApi.delete(comment);

        stringRedisTemplate.delete(StrUtil.format("publish_like_comment_{}_{}",userId,publishId));
        return ResponseEntity.ok(count);
    }

    public ResponseEntity commentLove(String publishId) {

        //设置点赞的可变属性
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        Long userId = UserHolder.findUser().getId();
        comment.setUserId(userId);
        comment.setPubType(1);
        comment.setCommentType(3);

        Integer count = commentApi.save(comment);

        //放入redis代表当前登录用户对某个动态点过赞 "comment_like_登录用户_动态id"
        stringRedisTemplate.opsForValue().set(StrUtil.format("publish_love_comment_{}_{}",userId,publishId),"1"); //1代表点赞

        return ResponseEntity.ok(count);
    }

    public ResponseEntity unLove(String publishId) {
        //设置点赞的可变属性
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        Long userId = UserHolder.findUser().getId();
        comment.setUserId(userId);
        comment.setPubType(1);
        comment.setCommentType(3);

        Integer count = commentApi.delete(comment);

        stringRedisTemplate.delete(StrUtil.format("publish_love_comment_{}_{}",userId,publishId));
        return ResponseEntity.ok(count);
    }


    public ResponseEntity findByPublishId(String publishId) {

        // 根据publishId获取publish对象
        Publish publish=publishApi.findById(publishId);
        // 获取userInfo数据
        UserInfo userInfo = userInfoApi.findByUser(publish.getUserId());
        // 组装publishVo 进行返回
        PublishVo publishVo = new PublishVo();
        publishVo.setUserInfo(userInfo);
        publishVo.setPublish(publish);
        return ResponseEntity.ok(publishVo);

    }

    public ResponseEntity findComments(String movementId, Integer page, Integer pagesize) {

        // 分页查询comment数据
        PageBeanVo pageBean=commentApi.findComments(movementId,page,pagesize);
        List<Comment> items = (List<Comment>) pageBean.getItems();
        List<CommentVo> commentVoList=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(items)){
            for (Comment comment : items) {
                // 查询userInfo的数据
                UserInfo userInfo = userInfoApi.findByUser(comment.getUserId());
                // 组装commentVo
                CommentVo commentVo = new CommentVo();
                BeanUtils.copyProperties(userInfo,commentVo);
                commentVo.setCreateDate(RelativeDateFormat.format(new Date(comment.getCreated())));
                commentVo.setLikeCount(comment.getLikeCount());
                commentVo.setContent(comment.getContent());
                commentVoList.add(commentVo);
            }
        }

        //封装pageBean返回
        pageBean.setItems(commentVoList);
        return ResponseEntity.ok(pageBean);

    }

    public ResponseEntity addComments(String publishId, String content) {

        //设置点赞的可变属性
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));
        Long userId = UserHolder.findUser().getId();
        comment.setUserId(userId);
        comment.setPubType(1);
        comment.setCommentType(2);
        comment.setContent(content);
        commentApi.save(comment);
        return ResponseEntity.ok(null);
    }
}
